import React from 'react';
import { Icon, Button, Tabs, Row, Col, notification, Modal, message } from 'antd';
import { withRouter } from 'react-router';
import axios from 'axios';
import store from '../../redux/index';
import './index.less';
import RoleTree from './Tree/index.jsx';
import GroupFrom from './GroupFrom/index.jsx';
import JurisdictionFrom from './JurisdictionFrom/index.jsx';
import RelationFrom from './Relation/index.jsx';

const TabPane = Tabs.TabPane;
const ButtonGroup = Button.Group;
const confirm = Modal.confirm;

class Groups extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      data: {
        Num: '',
        parentID: '',
        parentIdOff: false
      },
      MenuOff: '',
      visible: false,
      RelationVisible: false,
      tableUpdate: false
    };
  }

  // 提示框
  openNotification = (type, Message) => {
    notification[type]({
      message: Message,
    });
  };

  takeID = (ID, parentID) => {
    // console.log('---------id:' + ID);
    let oData = this.state.data;
    oData.Num = ID;
    oData.parentID = parentID;
    this.setState({
      data: oData,
      tableUpdate: false
    });
  }

  updataMenu = (MenuOff) => {
    this.setState({
      MenuOff: MenuOff
    });
  }
  // 编辑角色菜单
  editGroupMenu = () => {
    // console.log('编辑'+this.state.data.Num);
    if (this.state.data.Num !== '') {
      this.getMenuData(this.state.data.Num);
      store.dispatch({ type: 'changeGroupBtnsStatus', GroupBtnsStatus: false });
      store.dispatch({ type: 'changeGroupBtnsUpate', GroupBtnsUpate: true });
      store.dispatch({ type: 'changeGroupBtnsShow', GroupBtnsShowStatus: true });
      store.dispatch({ type: 'GroupDeleteValue', GroupDeleteValue: false });
    } else {
      this.openNotification('warning', '请选择菜单');
    }
  }
  // 添加角色菜单
  addGroupMenu = () => {
    let storeData = store.getState().getGroup.GroupData;
    if (this.state.data.Num === '') {
      // console.log('为空');
      storeData.parentId = -1;
    } else {
      storeData.parentId = this.state.data.Num;
      // console.log('不为空'+this.state.data.Num)
      storeData = {
        code: '',
        description: '',
        groupType: '',
        id: this.state.data.Num,
        name: '',
        parentId: this.state.data.parentID,
        path: '',
      };
    }
    // console.log(this.state.data.parentID+'----------');
    store.dispatch({ type: 'changeGroupBtnsStatus', GroupBtnsStatus: false });
    store.dispatch({ type: 'GroupData', GroupData: storeData });
    store.dispatch({ type: 'changeGroupBtnsUpate', GroupBtnsUpate: false });
    store.dispatch({ type: 'changeGroupBtnsShow', GroupBtnsShowStatus: false });
  }
  // 删除菜单
  showDeleteConfirm = () => {
    const _this = this;
    confirm({
      title: '删除',
      content: '此操作将永久删除，是否继续？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        let parentid = store.getState().getGroup.GroupData.parentId;
        let ID = store.getState().getGroup.GroupData.id;
        if (parentid !== '' && ID !== '') {
          _this.deleteMenu(ID);
        } else {
          _this.openNotification('warning', '请选择菜单项');
        }

        // console.log(store.getState().changeBtnsStatus.MenuData);

      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  deleteMenu = (ID) => {
    const _this = this;
    const Token = sessionStorage.getItem('token');
    axios.delete('/api/admin/group/' + ID, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      }
    })
      .then(function(response) {
        // console.log(response);
        if (response.data.status === 200) {
          _this.updataMenu('deleteOk');
          _this.openNotification('success', '成功', '删除成功');
        }
      })
      .catch(function(error) {
        console.log(error);
        message.error('服务器开小差啦，请重试！');
      });
  }

  getMenuData = (ID) => {
    const _this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/group/' + ID,
      headers: {
        Authorization: Token
      }
    })
      .then(function (response) {
        _this.setState({
          intData: response.data.data
        });
        let storeData = store.getState().getGroup.GroupData;
        storeData = {
          code: _this.state.intData.code,
          description: _this.state.intData.description,
          groupType: _this.state.intData.groupType,
          id: _this.state.intData.id,
          name: _this.state.intData.name,
          parentId: _this.state.intData.parentId,
          path: _this.state.intData.path,
        };
        store.dispatch({ type: 'GroupData', GroupData: storeData });
      })
      .catch(function (error) {
        console.log(error);
        message.error('服务器开小差啦，请重试！');
      });

  }
  // 权限分配弹框显示
  showModal = () => {
    // console.log(this.state.data.Num+'=========');
    if (this.state.data.Num) {
      this.setState({
        visible: true,
        tableUpdate: true
      });
      store.dispatch({ type: 'ChangeID', ChangeID: this.state.data.Num });
      store.dispatch({ type: 'GroupOff', GroupOff: true });
    } else {
      this.openNotification('success', '请选择角色类型菜单！');
    }
  }
  handleChancel = () => {
    this.setState({
      visible: false,
    });
  }

  handleCreate = () => {
    this.setState({
      visible: false,
    });
  }

  ResourcesCreate = (_this) => {
    // console.log(1111111111111111+'--'+this.state.data.Num);
    let SaveCheckedKeys = store.getState().getGroup.checkedKeys;
    if (SaveCheckedKeys.checked) {
      // console.log('checked'+SaveCheckedKeys.checked);
      this.Division(SaveCheckedKeys.checked, 'updata');
    } else {
      // console.log(SaveCheckedKeys);
      this.Division(SaveCheckedKeys);
    }

  }
  // 关联用户弹框
  RelationShow = () => {
    // console.log(this.state.data.Num+'=========');
    if (this.state.data.Num) {
      this.setState({
        RelationVisible: true,
      });
      const Token = sessionStorage.getItem('token');
      axios({
        method: 'get',
        url: '/api/admin/group/' + this.state.data.Num + '/user',
        headers: {
          Authorization: Token
        },
      })
        .then(function (response) {
          if (response.data.code === 200) {
            store.dispatch({ type: 'ChangeMembers', GroupMembers: response.data.data.members });
            store.dispatch({ type: 'ChangeMembersUser', GroupMembersUser: response.data.data.leaders });
            store.dispatch({ type: 'ChangeLeaders', GroupLeaders: response.data.data.leaders });
          }
        })
        .catch(function (error) {
          console.log(error);
          message.error('服务器开小差啦，请重试！');
        });
    } else {
      this.openNotification('success', '请选择角色类型菜单！');
    }
  }

  RelationChancel = () => {
    this.setState({
      RelationVisible: false,
    });
    store.dispatch({ type: 'ChangeMembers', GroupMembers: [] });
  }
  // 保存关联用户
  RelationCreate = () => {
    const _this = this;
    let oData = [];
    store.getState().getGroup.GroupMembers.forEach(item => {
      oData.push(item.id);
    });
    const members = oData;
    const leaders = store.getState().getGroup.GroupLeaders;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'PUT',
      url: '/api/admin/group/' + this.state.data.Num + '/user?members=' + members + '&leaders=' + leaders,
      headers: {
        Authorization: Token
      },
    })
      .then(function (response) {
        if (response.code === 200 || response.data.code === 200) {
          _this.openNotification('success', '保存成功');
        } else {
          _this.openNotification('warning', '保存失败');
        }
      })
      .catch(function (error) {
        console.log(error);
        message.error('服务器开小差啦，请重试！');
      });
    this.setState({
      RelationVisible: false,
    });
  }
  Division = (arry, updata) => {
    let strNum = '';
    for (let i = 0; i < arry.length; i++) {
      if (i >= arry.length - 1) {
        strNum += arry[i];
      } else {
        strNum += arry[i] + ',';
      }
    }

    if (updata === 'updata') {
      this.SaveData(strNum);
    }

    this.handleChancel();
    // console.log(strNum);
  }
  // 保存权限分配菜单选项
  SaveData = (menuTrees) => {
    const _this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'post',
      url: '/api/admin/group/' + this.state.data.Num + '/authority/menu?menuTrees=' + menuTrees,
      headers: {
        Authorization: Token
      },
    })
      .then(function (response) {
        _this.openNotification('success', '成功', '修改成功');
      })
      .catch(function (error) {
        console.log(error);
        message.error('服务器开小差啦，请重试！');
      });
  }

  render() {
    return (
      <Tabs defaultActiveKey="1" type="card">
        <TabPane tab="角色类型" key="1">
          <ButtonGroup>
            <Button type="primary" onClick={this.addGroupMenu}><Icon type="plus" />添加</Button>
            <Button type="primary" onClick={this.editGroupMenu}><Icon type="edit" />编辑</Button>
            <Button type="primary" onClick={this.showDeleteConfirm}><Icon type="delete" />删除</Button>
            <Button type="primary" onClick={this.showModal}><Icon type="schedule" />权限分配</Button>
            <Button type="primary" onClick={this.RelationShow}><Icon type="user-add" />关联用户</Button>
          </ButtonGroup>
          <div className="roleCt">
            <Row>
              <Col span={6}>
                <div className="TreeBox">
                  <RoleTree takeID={this.takeID} MenuOff={this.state.MenuOff} getMenuData={this.getMenuData} oData={this.state.data} />
                </div>
              </Col>
              <Col span={18}>
                <div className="GroupManagerFrom">
                  <GroupFrom ID={this.state.data.Num} oData={this.state.data} updataMenu={this.updataMenu} />
                </div>
                {/* <div className='MenuTable'>
                  <MenuManagerTable ID={this.state.data.Num}/>
                </div> */}
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                <JurisdictionFrom
                  ID={this.state.data.Num}
                  tableUpdate={this.state.tableUpdate}
                  oData={this.state.data}
                  visible={this.state.visible}
                  onCancel={this.handleChancel}
                  onSave={this.ResourcesCreate}
                />
              </Col>
            </Row>
            <Row>
              <Col span={24}>
                {this.state.RelationVisible ? <RelationFrom
                  ID={this.state.data.Num}
                  visible={this.state.RelationVisible}
                  onCancel={this.RelationChancel}
                  onSave={this.RelationCreate}
                /> : ''}
              </Col>
            </Row>
          </div>
        </TabPane>
        {/* <TabPane tab='部门类型' key='2'>Content of Tab Pane 2</TabPane>
              <TabPane tab='自定义类型' key='3'>Content of Tab Pane 3</TabPane> */}
      </Tabs>
    );
  }
}

export default withRouter(Groups);